﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Middle.Response.customs;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Redis;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.middle;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;

namespace BenCaoXuan.Service.Instance.middle
{
    [Inject_]
    public class MiddleLogin_Service : Base_Service, I_MiddleLogin_Service
    {
        private readonly Login_IOC _login_IOC;
        private readonly RedisStringService _redisStringService;
        private readonly IConfiguration _configuration;

        public MiddleLogin_Service(Login_IOC login_IOC,
            RedisStringService redisStringService,
           IConfiguration configuration) {
            _login_IOC = login_IOC;
            _redisStringService = redisStringService;
            _configuration = configuration;
        }
        /// <summary>
        /// 检查登录
        /// </summary>
        /// <param name="code"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public Customs_Dto Check_Middle_Login(string code, string account)
        {
            var redis = _configuration["Redis:Keys:Middle_Check_Login"];


            //获取redis中的用户信息
            var customs = _redisStringService.Get<string>(code);
            if (!string.IsNullOrEmpty(customs))
            {
                return JsonConvert.DeserializeObject<Customs_Dto>(customs)!;
            }



            var jwt = _redisStringService.Get<string>(redis + account);//code
            if (code == jwt)
            {
                //返回登录的用户信息
                var e = _login_IOC._custom_EFCore.GetAll(d => d.CPhone == account)
                     .Select(d => new Customs_Dto()
                     {
                         id = d.CId,
                         account = d.CPhone,
                         name = d.CName,
                         isConvert=d.CIsConvert
                     }).Single();
                //将用户存在redis中
                _redisStringService.Set(code, JsonConvert.SerializeObject(e), DateTime.Now.AddSeconds(120));
                return e;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 初始化员工密码
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Init_User()
        {
            var customs = await _login_IOC._custom_EFCore.GetAll().ToListAsync();
            customs.ForEach(d =>
            {
                var salt = Config.GUID2();
                d.CSalt = salt;
                d.CPassword = EncryptUtil.LoginMd5("123456", salt);
            });

            _login_IOC._custom_EFCore.UpdateRange(customs);
            _login_IOC._custom_EFCore.SaveChanges();

            return Get_Result(0);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Logins(Login_Dto dto)
        {
            var iq = _login_IOC._custom_EFCore.GetAll(d => d.CPhone == dto.account);
            if (!await iq.AnyAsync())
            {
                return Get_Result(-1, "账号或者密码错误");
            }

            var customs = await iq.SingleAsync();
            var pwd = EncryptUtil.LoginMd5(dto.password!, customs.CSalt!);
            if (customs.CPassword != pwd)
            {
                return Get_Result(-1, "账号或者密码错误");
            }

            //添加登录日志
            SysCustomerLoginLog sysCustomerLoginLog = new SysCustomerLoginLog()
            {
                LlId = Config.GUID2(),
                LlCid = customs.CId,
                LlCode = dto.code,
                LlCname = customs.CName!,
                LlIpaddress = Config.GetIp(),
                LlLoginTime = DateTime.Now,
                LlRemark = customs.CRemark,
            };
            _login_IOC._sysCustomerLoginLog_EFCore.Add(sysCustomerLoginLog);
            //事务
            var result = _login_IOC._sysCustomerLoginLog_EFCore.Transactions(_login_IOC._custom_EFCore);

            //保存code到redis
            var jwt = _configuration["Redis:Keys:Middle_Check_Login"];


            _redisStringService.Set<String>(jwt + customs.CPhone, dto.code!, DateTime.Now.AddSeconds(86400));

            return Get_Result(result ? 0 : -1);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="account">用户账号（手机号）</param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Logout(string account)
        {
            try
            {
                // 1. 清除Redis中存储的登录状态（对应登录时保存的code）
                var redisKey = _configuration["Redis:Keys:Middle_Check_Login"] + account;
                await _redisStringService.RemoveAsync(redisKey);

                // 2. 记录退出日志
                var customer = await _login_IOC._custom_EFCore.GetAll(c => c.CPhone == account)
                    .FirstOrDefaultAsync();

                if (customer != null)
                {
                    var logoutLog = new SysCustomerLoginLog
                    {
                        LlId = Config.GUID2(),
                        LlCid = customer.CId,
                        LlCname = customer.CName,
                        LlIpaddress = Config.GetIp(),
                        LlLoginTime = DateTime.Now,
                        LlRemark = "用户主动退出登录",
                    };

                    _login_IOC._sysCustomerLoginLog_EFCore.Add(logoutLog);
                    await _login_IOC._sysCustomerLoginLog_EFCore.SaveChangesAsync();
                }


                return Get_Result(0, "退出成功");
            }
            catch (Exception ex)
            {
                return Get_Result(-1, $"退出失败：{ex.Message}");
            }
        }


    }
}
